// pages/wxPay/wxPay.js
//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    payParam: '',
    payokParam: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('option:' + JSON.stringify(options));
    let param = decodeURIComponent(options.payParam);
    // console.log(param);
    let pay = JSON.parse(param);
    this.setData({
      payParam: pay,
    })
    console.log('payParam:' + param);
    console.log(this.data.payParam);
    console.log(app.globalData.userInfo);
    this.pay();
  },
  /*
  调起微信支付 
  @param 支付价格，不填写默认为1分钱
  */
  pay: function () {
    var that = this;
    var openid = app.globalData.userInfo.openid;
    wx.request({
      url: app.globalData.api + 'xcxpay.php?action=pay',
      method: "POST",
      data: {
        openid: openid,
        orderid: that.data.payParam.orderId,
        orderpara1: that.data.payParam.orderpara1,
        orderpara2: that.data.payParam.orderpara2,
        orderpara3: that.data.payParam.orderpara3
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        var data = res.data;
        console.log(data);
        if (data.state > 0){
          that.setData({
            payokParam: {
              timeStamp: data['timeStamp'],
              nonceStr: data['nonceStr'],
              package: data['package'],
              signType: data['signType'],
              paySign: data['paySign']
            }
          });
          that.confirmPay();
        }else{
          wx.showToast({
            title: '创建订单失败:' + JSON.stringify(data),
            icon: 'none',
          })
        }
      }
    });

  },
  //采用小程序支付
  confirmPay: function () {
    console.log('wxpay');
    const _this = this;
    wx.requestPayment({
      "timeStamp": _this.data.payokParam.timeStamp,
      "nonceStr": _this.data.payokParam.nonceStr,
      "package": _this.data.payokParam.package,
      "signType": _this.data.payokParam.signType,
      "paySign": _this.data.payokParam.paySign,
        //支付成功的回调
      'success': function (res) {      
        console.log('success:' + JSON.stringify(res));
        wx.showToast({
          title: '支付成功',
          icon: 'succes',
          duration: 1000,
          mask: true,
          complete: function (res) {
            //你可以在这里支付成功以后，再跳会webview页，并把支付成功状态传回去
            wx.navigateTo({
              url: '../index/index?payOk=true'
            });
          }
        });
      },
      //支付失败的回调
      'fail': function (res) {
        console.log('fail:' + JSON.stringify(res));
        wx.showToast({
          title: '支付失败:' + JSON.stringify(res),
          icon: 'none',
        })

      },
      'complete': function (res) {
        console.log('complete:' + JSON.stringify(res));
      }
    })
  }
})